package com.heima.wemedia.filter;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * 1、拦截请求
 * 2、获取请求头userId, 存到ThreadLocal 当前线程中
 * @Version: V1.0
 */
@Component
@Slf4j
@WebFilter(urlPatterns = "/**", filterName ="wmTokenFilter" )
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        //1 request 转成 HttpServletRequest
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;

        //2 header获取userId
        String userId = servletRequest.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));

            // 存到ThreadLocal
            WmThreadLocalUtils.setUser(wmUser);
        }

        chain.doFilter(servletRequest, servletResponse);
    }
}
